using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using SiteManager;

/// <summary>
/// PAGE TO MANAGE DENTISTS
/// </summary>
/// <remarks>
/// AUTHOR  : KAJAL MANDAL  
/// DATE    : MAY 15, 2007
/// </remarks>
public partial class Admin_Dentist_Ad_Dentist_Manage : System.Web.UI.Page
{
    Manager mgr = new Manager(true,"ConnectionString");
    Dentist objDentist = new Dentist();
    string top10 = "top 10";
    private bool fd;
    protected void Page_Load(object sender, EventArgs e)
    {

        lblMsg.Text = "";

        if (!Page.IsPostBack)
        {
            fd = false;              //default value of Featured Dentist Display Flag is set to false
            BindList();
            BindGrid();
            pnlHint.Visible = true;
        }
        else
        {
            //Fetch the Featured Dentist Display Flag value from View-State
            fd = Convert.ToBoolean(ViewState["fd"]);
        }
        if (txtEmail.Text.Length > 0 || txtName.Text.Length > 0 || ddStateList.SelectedIndex > 0)
        {
            pnlHint.Visible = false;
            top10 = "";
        }
        else
            pnlHint.Visible = true;

        foreach (GridViewRow rv in GridView1.Rows)
        {
            CheckBox chkRow = (CheckBox)rv.FindControl("RowLevelCheckBox");
            chkRow.Attributes.Add("onclick", "ChangeHeaderAsNeeded();");
            ClientScript.RegisterArrayDeclaration("CheckBoxIDs", String.Concat("'", chkRow.ClientID, "'"));
        }

        lbltotDentists.Text = getTotal().ToString();
        //Get Currently Featured Dentist's Detail : Code by Ajay Kumar Singh
        getRecentFeaturedDentist();
    }

    /// <summary>
    /// Function to check featured Dentist from tbl_bidding
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    //Code by Ajay Kumar Singh - 29/01/07
    private bool checkkFeaturedDentist(int id)
    {
        // NEW QUERY TO HIGHLIGHT FEATURE DENTIST
        //  string strQuery = "Select Dr_Id from tbl_bidding where Trx_Status=1 and Dr_Id=" + id + "";  //OLD QUERY
        string strQuery = "Select Id from tbl_Dentists where isdelete=0 and featuredoctypeid > 0 and Id=" + id + "";  //NEW QUERY
        //     Response.Write(strQuery + "<BR>");
        SqlDataReader drResult = mgr.ExecuteQuery(strQuery);
        if (drResult.Read())
        {
            drResult.Close();
            return true;
        }
        else
        {
            drResult.Close(); 
            return false;
        }
    }

    /// <summary>
    /// binds the grid view
    /// </summary>
    public void BindGrid()
    {
        try
        {

            string sql = "select " + top10 + " id,fname+' '+lname as Name,title,city,state,phone,email from tbl_Dentists d where isdelete=0";
            if (fd)
            {
                sql = "select id,fname+' '+lname as Name,title,city,state,phone,email from tbl_Dentists d where isdelete=0";
            }
            //string sql = "select " + top10 + " d.id, d.fname+ ' ' + d.lname as Name,d.title,d.city,d.state,d.phone,d.email, isnull(b.trx_status,0) fd from tbl_Dentists d left join tbl_bidding b on b.dr_id=d.id where d.isdelete=0 and b.trx_status=1";

            if (txtName.Text.Trim() != "")
                sql += " and (d.FName + ' ' + d.LName LIKE '%" + txtName.Text.Trim() + "%')";
            if (ddStateList.SelectedValue != "0")
            { sql += " and d.state='" + ddStateList.SelectedValue + "'"; }

            if (txtEmail.Text.Trim() != "")
            { sql += " and d.email like'%" + txtEmail.Text.Trim().Replace("'", "''") + "%'"; }

            ///IF ONLY FEATURE DENTIST IS TO BE DISPLAYED: K, 16 FEBRUARY 2007
            if (fd)
            {
                // COMMENTED TO CHANGE FEATURED DENTIST ACCORDING TO NEW FUNCTIONALITY AFTER IMPLEMENTING YOURPAY
                // Change Date: 20th Dec 2007
                //  sql += " and d.id in (select dr_id from tbl_bidding where trx_status=1) ";  // OLD CODE
                sql += " and d.id in (select DentistId from DentistSubscription ds INNER JOIN tbl_Dentists as d ON ds.DentistId = d.Id WHERE isdelete = 0 and d.featuredoctypeId > 0) ";  // NEW CODE
            }
            ///KCODE ENDS
            sql += "order by d.id desc";
            //Response.Write(sql);
            DataSet ds = mgr.ExecuteQuery(sql, "tblDentist");
            if (ds.Tables[0].Rows.Count > 0)
            {
                GridView1.DataSource = ds;
                GridView1.PageSize = Convert.ToInt32(Session["AdminPageSize"].ToString());  //PageSize="<%=Session['AdminPageSize']%>
                GridView1.Visible = true;
                lblMsg.Visible = false;
                GridView1.DataBind();

                //Check Featured Dentist :Code by-Ajay Kumar Singh-29/01/07
                foreach (GridViewRow rv in GridView1.Rows)
                {
                    int drID = Convert.ToInt32(GridView1.DataKeys[rv.RowIndex].Value.ToString()); //Dentist's ID                    

                    bool resp = checkkFeaturedDentist(drID);
                    if (resp == true)
                    {
                        //Change Dr. Name color to Red
                        GridView1.Rows[rv.RowIndex].Cells[3].ForeColor = System.Drawing.Color.Red;
                    }
                }

            }
            else
            {
                lblMsg.Text = "No Records found!!<br>Please click the Add Dentist link on the left panel to add a new dentist.";
                lblMsg.ForeColor = System.Drawing.Color.Red;
                GridView1.Visible = false;
                lblMsg.Visible = true;
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }

    private void SaveDataAfterApproval(int drID)
    {
        //Write Code to add the processed value in database
        objDentist.DentistId  = drID;
        objDentist.TransactionId = "0";
        objDentist.TransactionDate = DateTime.Now.ToString();//need to confirm  which date should be add ?? R_Time or startdate.
        objDentist.TransactionAmount = "1999";
        objDentist.SubscriptionId = "1234";
        objDentist.SubscriptionType = "Annual";
        objDentist.FeatureDentistTypeId = 3;
        SqlDataReader objDataReader = null;
        objDataReader = mgr.ExecuteQuery("select tbl_speciality.Name,tbl_speciality.id,tbl_Dentists.fName from tbl_Dentists inner join tbl_speciality  on tbl_speciality.id =tbl_Dentists.SpecialityID  and tbl_Dentists.id=" + drID);

        if (objDataReader.HasRows)
        {
            objDataReader.Read();
            string id = objDataReader["id"].ToString();
            if (!Equals(id, string.Empty))
            {
                objDentist.SpecialityId = Convert.ToInt32(objDataReader["id"].ToString());
            }
            objDataReader.Close();
        }
        else
        {
            objDentist.SpecialityId = 0;
            objDataReader.Close();
        }

        objDentist.SubSpecialityId = 0;

        objDentist.photo = string.Empty;
        objDentist.prof_desc = string.Empty;
        objDentist.website = string.Empty;
        //objDentist.CardNumber = txtcardnumber.Text;
        //objDentist.ExpYear = expyear;
        //objDentist.ExpMonth = expmonth;
        //   Response.Write(docimage.Length + "============");
        //   objDentist.image = docimage;
        //   localFunction th = new localFunction();

        //   objDentist.th_image = th.getThumbnaleImage(docimage,80,100);
        //        Response.Write("IN IF");



        mgr.ExecuteScalarQuery("update tbl_Dentists set FeatureDocTypeId ='" + objDentist.FeatureDentistTypeId + "' where id ='" + objDentist.DentistId + "'");
        //     Response.Write("IN SAVE");
        objDentist.InsertDentistSubscription();
    }


    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
            string delSql = "update tbl_Dentists set isdelete=1 where id=" + id;

            // Edited By: Deepak
            // To remove the error of open datareader
            // Date: 09/01/2008
            // mgr.ExecuteQuery(delSql);
            mgr.ExecuteScalarQuery(delSql);
            // Edited Code Ends

            SqlParameter[] sqlParam = new SqlParameter[3];

            sqlParam[0] = new SqlParameter("@Dr_ID", SqlDbType.Int);
            sqlParam[1] = new SqlParameter("@AdminID", SqlDbType.Int);
            sqlParam[2] = new SqlParameter("@ActionPerformed", SqlDbType.VarChar, 100);

            sqlParam[0].Value = id;
            sqlParam[1].Value = Convert.ToInt32(Session["ADMIN_ID"]);
            sqlParam[2].Value = "DENTIST DELETED";

            mgr.ExecuteUpdate("LOG_ADMIN_ACTIVITY", sqlParam);

            BindGrid();
            lbltotDentists.Text = getTotal().ToString();
        }
        catch (Exception)
        {
      //      Response.Write(ex.ToString());
        }
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.Header)
        {
            CheckBox chkBox = (CheckBox)e.Row.FindControl("HeaderLevelCheckBox");
            chkBox.Attributes.Add("onclick", "ChangeAllCheckBoxStates(this.checked);");
        }

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            try
            {
                LinkButton lnk = (LinkButton)e.Row.FindControl("lnkDelete");
                lnk.Attributes.Add("onclick", "return confirm('Are you sure to delete this record?')");


            }
            catch (Exception es)
            {
                Response.Write(es.ToString());
            }
        }

    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        BindGrid();
    }

    protected void butSerach_Click(object sender, EventArgs e)
    {
        BindGrid();
    }
    private int getTotal()
    {
        string sql = "Select Count(id)  from tbl_Dentists where isdelete=0";
        int CountRec = (int)mgr.ExecuteScalarQuery(sql);
        return CountRec;
    }
    private void BindList()
    {

        mgr.BindList("select stateid,name from tbl_states order by name", "Name", "StateId", this.ddStateList, "");
        ddStateList.Items.Insert(0, new ListItem("--Any--", "0"));
    }



    protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Del")
        {
            foreach (GridViewRow rv in GridView1.Rows)
            {
                CheckBox chk = (CheckBox)rv.FindControl("RowLevelCheckBox");
                if (chk.Checked)
                {
                    string id = GridView1.DataKeys[rv.RowIndex].Value.ToString();
                    string sql = "update tbl_Dentists set isdelete=1 where id=" + id;

                    // Edited By: Deepak
                    // To remove the error of open datareader
                    // Date: 09/01/2008
                    // mgr.ExecuteQuery(sql);
                    mgr.ExecuteScalarQuery(sql);
                    // Edited Code Ends
                }
            }
            BindGrid();
            lbltotDentists.Text = getTotal().ToString();
        }
    }


    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    //Author: Ajay Kumar Singh
    //Date: 27/01/2007

    protected void chkFD_CheckedChanged(object sender, EventArgs e)
    {
        int drID = 0;
        string drName = string.Empty;

        foreach (GridViewRow gvr in GridView1.Rows)
        {
            CheckBox chkFD = (CheckBox)gvr.FindControl("chkFD");
            if (chkFD.Checked)
            {
                drID = Convert.ToInt32(GridView1.DataKeys[gvr.RowIndex].Value.ToString()); //Dentist's ID
               // drName = GridView1.Rows[gvr.RowIndex].Cells[2].Text; //Commented by Wahaj Khan Feb 28 2010
                drName = GridView1.Rows[gvr.RowIndex].Cells[3].Text; //Added by Wahaj Khan Feb 28 2010
                //Response.Write(drName);
                
                //Code to update table tbl_fdListing
                //string strSql = "Update tbl_fdListing set dr_id=" + drID;
                //mgr.ExecuteUpdate(strSql);                

                SqlParameter[] spm = new SqlParameter[2];
                spm[0] = new SqlParameter("@Dr_ID", SqlDbType.Int);
                spm[1] = new SqlParameter("@RetVal", SqlDbType.Int);
                spm[1].Direction = ParameterDirection.Output;

                spm[0].Value = drID;
                mgr.ExecuteUpdate("usp_DeclareFeaturedDentist", spm);
                int retval = Convert.ToInt32(spm[1].Value.ToString());
                if (retval > 0) //every thing fine.
                {
                    //Fetch details of currently featured Dentist.
                    getRecentFeaturedDentist();
                }
                else
                {
                    //string strBreak="\\n";
                    //Response.Write("<script>alert('"+drName+"')</script>");

                    //The selected Dentist, Dr.<name>, is not a featured Dentist. Only featured dentist can be placed on the homepage (Dentist marked in red are featured dentist). 
                   // Response.Write("<script>alert('The selected dentist, Dr. " + drName + ", is not a featured dentist. \\nOnly featured dentist can be placed on the homepage (Dentists marked in red are featured dentists).')</script>");
                    SaveDataAfterApproval(drID);///To be written by Wahaj Khan
                    //Response.Write("<script>alert('" + drName + " is not a Featured Dentist, \\nso he could not be placed in home page.')</script>");                    
                }

            }
        }
        BindGrid();
        //getRecentFeaturedDentist();
    }
/***********************************************Function added by Wahaj Khan********************************************/
    protected void chkUSFD_CheckedChanged(object sender, EventArgs e)
    {
        int drID = 0;
        string drName = string.Empty;

        foreach (GridViewRow gvr in GridView1.Rows)
        {
            CheckBox chkUSFD = (CheckBox)gvr.FindControl("chkUSFD");
            if (chkUSFD.Checked)
            {
                drID = Convert.ToInt32(GridView1.DataKeys[gvr.RowIndex].Value.ToString()); //Dentist's ID
                drName = GridView1.Rows[gvr.RowIndex].Cells[3].Text; //Dentist's Name

                //Response.Write(drName);

                //Code to update table tbl_fdListing
                //string strSql = "Update tbl_fdListing set dr_id=" + drID;
                //mgr.ExecuteUpdate(strSql);                

                SqlParameter[] spm = new SqlParameter[2];
                spm[0] = new SqlParameter("@Dr_ID", SqlDbType.Int);
                spm[1] = new SqlParameter("@RetVal", SqlDbType.Int);
                spm[1].Direction = ParameterDirection.Output;

                spm[0].Value = drID;
                mgr.ExecuteUpdate("usp_DeclareFeaturedDentist", spm);
                int retval = Convert.ToInt32(spm[1].Value.ToString());
                if (retval > 0) //every thing fine.
                {
                    //Fetch details of currently featured Dentist.
                    mgr.ExecuteScalarQuery("delete from Dentistsubscription where DentistId ='" + drID + "'");
                    mgr.ExecuteScalarQuery("delete from tbl_dntpremium where dnt_id ='" + drID + "'");
                    mgr.ExecuteScalarQuery("update tbl_Dentists set FeatureDocTypeId ='" + DBNull.Value + "' where id ='" + drID + "'");
                }
                else
                {
                    //string strBreak="\\n";
                    //Response.Write("<script>alert('"+drName+"')</script>");

                    //The selected Dentist, Dr.<name>, is not a featured Dentist. Only featured Dentists can be placed on the homepage (Dentists marked in red are featured Dentists). 
                    Response.Write("<script>alert('The selected Dentist, Dr. " + drName + ", is not a featured Dentist. \\nOnly featured Dentists would be unsubscribed.')</script>");
                    //SaveDataAfterApproval(drID);
                    //Response.Write("<script>alert('" + drName + " is not a Featured Dentist, \\nso he could not be placed in home page.')</script>");                    
                }

            }
        }
        BindGrid();
    }

 /***********************************************End of Function added by Wahaj Khan********************************************/

    //Function get Currently Featured Dentist's Detail
    void getRecentFeaturedDentist()
    {
        SqlDataReader drFeatured = null;
        System.Text.StringBuilder sbDetail = new System.Text.StringBuilder();

        drFeatured = mgr.ExecuteQuery("usp_getRecentFeaturedDentist");
        if (drFeatured.Read())
        {
            sbDetail.Append("<br/>&nbsp;Currently Featured Dentist is ");
            //sbDetail.Append("<Table>");            
            //sbDetail.Append("<tr><td align='left'>Name : </td><td align='left'>" + drFeatured["Name"].ToString() + "</td></tr>");
            //sbDetail.Append("<tr><td align='left'>Title : </td><td align='left'>" + drFeatured["Title"].ToString() + "</td></tr>");
            //sbDetail.Append("<tr><td align='left'>City : </td><td align='left'>" + drFeatured["City"].ToString() + "</td></tr>");
            //sbDetail.Append("<tr><td align='left'>State : </td><td align='left'>" + drFeatured["State"].ToString() + "</td></tr>");
            //sbDetail.Append("</Table>");
            sbDetail.Append("&nbsp;" + drFeatured["Name"].ToString() + " ;  " + drFeatured["City"].ToString() + " ,  " + drFeatured["State"].ToString());

            drFeatured.Close();
        }
        lblFeaturedDoc.Text = sbDetail.ToString();
    }

    /// <summary>
    /// On click of the Swap-Link, the Featured Dentist Display Flag value is swapped
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <remarks>
    /// Author  : Kajal Mandal
    /// Date    : 16 February 2006
    /// </remarks>
    protected void lnkSwap_Click(object sender, EventArgs e)
    {
        fd = ((fd) ? false : true);                     //swap the value of Featured dentist Display Flag
        if (fd)
        { lnkSwap.Text = "Show all dentist"; }
        else
        { lnkSwap.Text = "Show Featured dentist only"; }
        BindGrid();
        ViewState["fd"] = fd;                           //store the swapped value in view-state
    }
}

